import type { FormInstance } from 'element-plus'
import type { SystemPostOptionsType, SystemPostDataItemType } from './typings'
import { defineComponent, ref, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElSelect,
  ElOption,
  ElButton,
  ElMessage,
  ElIcon
} from 'element-plus'
import { CirclePlus, CircleClose } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import type { categoryEnum } from '~/store/system/typings'
import { handleTrim } from '~/utils/util'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '~/pages/system/index.module.scss'

export default defineComponent({
  name: 'SystemPostOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemPostOptionsType, { emit }) {
    const store = useStore()
    const systemPostState = useVuexGetters('systemPost', ['categorySelectList', 'categoryEnum'])
    const ruleFormRef = ref<FormInstance>()
    const title = { add: '新增', update: '编辑', read: '查看' }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    watch(
      () => props.visible,
      () => {
        if (props.visible) {
          store.dispatch('systemPost/GetDataDictionaryByCode', { code: 'post_category' }) // 岗位类型
        }
      }
    )

    return () => {
      const { type, visible } = props
      const optionsValidateForm = reactive<SystemPostDataItemType>(
        Object.assign(
          {
            category: '',
            postCode: '',
            leaderPost: '',
            isSystem: 0, // 是否全局 字段隐藏掉， 默认传0
            sort: undefined,
            remark: ''
          },
          props.record
        )
      )
      // 提交表单
      const handleSubmitForm = () => {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validate(async (valid) => {
          if (!valid) return
          // 去输入的前后空格
          optionsValidateForm.postCode = handleTrim(optionsValidateForm.postCode ?? '')
          optionsValidateForm.postName = handleTrim(optionsValidateForm.postName ?? '')
          optionsValidateForm.remark = handleTrim(optionsValidateForm.remark ?? '')

          const params = { ...optionsValidateForm }
          const res = await store.dispatch(
            type === 'add' ? 'systemPost/PostSystemPostAdd' : 'systemPost/PostSystemPostUpdate',
            params
          )
          if (res?.code === 200) {
            ElMessage({ type: 'success', message: '操作成功' })
            handleCloseModal()
          } else {
            ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
          }
        })
      }
      return (
        <ElDialog
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <CirclePlus />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>
                    <ElIcon>
                      <CircleClose />
                    </ElIcon>
                    取消
                  </ElButton>
                </>
              )
            }
          }
        >
          <div class={styles['systemPostOption-form']}>
            <ElForm label-width="100px" ref={ruleFormRef} model={optionsValidateForm}>
              <ElRow gutter={GUTTER}>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="category"
                    label="岗位类型"
                    rules={[{ required: true, message: '请选择 岗位类型', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      systemPostState.categoryEnum.value?.[optionsValidateForm.category!] || '无'
                    ) : (
                      <ElSelect
                        v-model={optionsValidateForm.category}
                        placeholder="请选择 岗位类型"
                        clearable
                      >
                        {systemPostState.categorySelectList?.value?.map((item: categoryEnum) => (
                          <ElOption
                            key={item?.dictKey}
                            label={item?.dictValue}
                            value={item?.dictKey!}
                          />
                        ))}
                      </ElSelect>
                    )}
                  </ElFormItem>
                </ElCol>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="postCode"
                    label="岗位编号"
                    rules={[{ required: true, message: '请输入 岗位编号', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.postCode
                    ) : (
                      <ElInput
                        v-model={optionsValidateForm.postCode}
                        placeholder="请输入 岗位编号"
                        clearable
                      />
                    )}
                  </ElFormItem>
                </ElCol>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="postName"
                    label="岗位名称"
                    rules={[{ required: true, message: '请输入 岗位名称', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.postName
                    ) : (
                      <ElInput
                        v-model={optionsValidateForm.postName}
                        placeholder="请输入 岗位名称"
                        clearable
                      />
                    )}
                  </ElFormItem>
                </ElCol>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="leaderPost"
                    label="是否领导"
                    rules={[{ required: true, message: '请选择 是否领导', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      parseInt(optionsValidateForm.leaderPost!, 10) === 1 ? (
                        '是'
                      ) : (
                        '否'
                      )
                    ) : (
                      <ElSelect
                        v-model={optionsValidateForm.leaderPost}
                        placeholder="请选择 是否领导"
                        clearable
                      >
                        <ElOption key={1} label="是" value={1} />
                        <ElOption key={0} label="否" value={0} />
                      </ElSelect>
                    )}
                  </ElFormItem>
                </ElCol>
                {/* <ElCol {...SPAN_STYLE_DOUBLE}> // 是否全局 字段隐藏掉， 默认传0
                  <ElFormItem
                    prop="isSystem"
                    label="是否全局"
                    rules={[{ required: true, message: '请选择 是否全局', trigger: 'change' }]}
                  >
                    {type === 'read'
                      ? (
                          parseInt(optionsValidateForm.isSystem!, 10) === 1
                            ? (
                                '是'
                              )
                            : (
                                '否'
                              )
                        )
                      : (
                      <ElSelect
                        v-model={optionsValidateForm.isSystem}
                        placeholder="请选择 是否全局"
                        clearable
                      >
                        <ElOption key={1} label="是" value={1} />
                        <ElOption key={0} label="否" value={0} />
                      </ElSelect>
                        )}
                  </ElFormItem>
                </ElCol> */}
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="sort"
                    label="排序"
                    rules={[{ required: true, message: '请输入 排序', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.sort
                    ) : (
                      <ElInputNumber
                        v-model={optionsValidateForm.sort}
                        min={0}
                        controls-position="right"
                        placeholder="请输入 排序"
                      />
                    )}
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElRow>
                <ElCol>
                  <ElFormItem prop="remark" label="岗位描述">
                    {type === 'read' ? (
                      optionsValidateForm.remark
                    ) : (
                      <ElInput
                        v-model={optionsValidateForm.remark}
                        autosize={{ minRows: 6, maxRows: 11 }}
                        type="textarea"
                        placeholder="请输入 岗位描述"
                        clearable
                      />
                    )}
                  </ElFormItem>
                </ElCol>
              </ElRow>
            </ElForm>
          </div>
        </ElDialog>
      )
    }
  }
})
